package com.micromall.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.micromall.utils.CommonEnvConstants;
import com.micromall.utils.HttpUtils;
import com.micromall.web.security.annotation.Authentication;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zhangzx on 16/3/25.
 * 支付回调通知
 */
@RestController
@RequestMapping(value = "/api")
@Authentication
public class WeixinJsapiAction {

	private static Logger logger = LoggerFactory.getLogger(WeixinJsapiAction.class);

	private static String JSAPI_TICKET;
	private static long   JSAPI_TICKET_EXPIRES_IN;

	private String getJsapiTicket() {
		if (JSAPI_TICKET == null || System.currentTimeMillis() >= JSAPI_TICKET_EXPIRES_IN) {
			refresh_jsapi_ticket();
		}
		return JSAPI_TICKET;
	}

	@Scheduled(cron = "0 0/10 * * * ?")
	public void refresh_jsapi_ticket() {
		logger.info("开始更新jsapi_ticket");
		String access_token = null;
		try {
			Map<String, String> params = new HashMap<>();
			params.put("appid", CommonEnvConstants.WEIXIN_APPID);
			params.put("secret", CommonEnvConstants.WEIXIN_APP_SECRET);
			params.put("grant_type", "client_credential");
			ResponseEntity<String> responseEntity = HttpUtils.executeGet("https://api.weixin.qq.com/cgi-bin/token", params, String.class);
			if (responseEntity.getStatusCode() == HttpStatus.OK && StringUtils.isNotEmpty(responseEntity.getBody())) {
				JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
				access_token = jsonObject.getString("access_token");
			}
			if (StringUtils.isEmpty(access_token)) {
				logger.error("获取access_token失败，接口结果：{}", responseEntity.getBody());
				return;
			}
		} catch (Exception e) {
			logger.error("获取access_token出错", e);
			return;
		}

		try {
			Map<String, String> params = new HashMap<>();
			params.put("access_token", access_token);
			params.put("type", "jsapi");
			ResponseEntity<String> responseEntity = HttpUtils.executeGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", params, String.class);
			String jsapi_ticket = null;
			if (responseEntity.getStatusCode() == HttpStatus.OK && StringUtils.isNotEmpty(responseEntity.getBody())) {
				JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
				if (jsonObject.containsKey("ticket")) {
					jsapi_ticket = jsonObject.getString("ticket");
					JSAPI_TICKET = jsapi_ticket;
					JSAPI_TICKET_EXPIRES_IN = System.currentTimeMillis() + (jsonObject.getInteger("expires_in") * 1000);
				}
			}
			if (StringUtils.isEmpty(jsapi_ticket)) {
				logger.error("获取jsapi_ticket失败，access_token:{}，接口结果：{}", access_token, responseEntity.getBody());
				return;
			}
		} catch (Exception e) {
			logger.error("获取jsapi_ticket出错，access_token:{}", access_token, e);
			return;
		}
		logger.info("jsapi_ticket已更新");
	}

	@RequestMapping("/weixin/jsapi_config")
	public com.micromall.web.resp.ResponseEntity<?> jsapi_config(HttpServletRequest request, String url) {
		String noncestr = RandomStringUtils.random(16, true, true);
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		Map<String, String> params = new HashMap<>();
		params.put("jsapi_ticket", getJsapiTicket());
		params.put("noncestr", noncestr);
		params.put("timestamp", timestamp);
		/*String url = request.getRequestURL().toString();
		if (StringUtils.isNotEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}*/
		params.put("url", url);
		logger.info("jsapi_config_params:{}", JSON.toJSONString(params));

		StringBuilder builder = new StringBuilder();
		List<String> keys = new ArrayList<>(params.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			builder.append(key).append("=").append(params.get(key)).append("&");
		}
		builder.deleteCharAt(builder.lastIndexOf("&"));
		logger.info("builder:{}", builder.toString());

		Map<String, String> data = Maps.newHashMap();
		data.put("appId", CommonEnvConstants.WEIXIN_APPID);
		data.put("nonceStr", noncestr);
		data.put("timestamp", timestamp);
		data.put("signature", DigestUtils.sha1Hex(builder.toString()));
		logger.info("jsapi_config:{}", JSON.toJSONString(data));
		return com.micromall.web.resp.ResponseEntity.Success(data);
	}

}
